package com.it.system.user.controller;

import com.it.system.educommonapi.entity.User;
import com.it.system.user.service.FileService;
import com.it.system.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;

    @GetMapping("/checkToken")
    public ResponseEntity<?> checkToken() {
        log.info("Checking token validity");
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body("Token无效");
        }

        // 返回用户名，表示token有效
        String currentUsername = authentication.getName();
        return ResponseEntity.ok("Token有效，用户名: " + currentUsername);
    }

    @PutMapping("/updateUser")
    public ResponseEntity<?> updateUser(@RequestBody User user) {
        log.info("Updating user info: {}", user);
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body("用户未登录");
        }

        // 验证用户ID是否匹配
        String currentUsername = authentication.getName();
        User currentUser = userService.getById(user.getId());
        if (currentUser == null || !currentUser.getUsername().equals(currentUsername)) {
            return ResponseEntity.status(403).body("无权修改其他用户信息");
        }

        // 只更新允许的字段
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setRealname(user.getRealname());
        updateUser.setIcon(user.getIcon());
        updateUser.setTelephone(user.getTelephone());

        // 更新用户信息
        boolean success = userService.updateById(updateUser);
        if (success) {
            return ResponseEntity.ok("更新成功");
        } else {
            return ResponseEntity.status(500).body("更新失败");
        }
    }
    
    /**
     * 上传用户头像 - 匹配前端请求路径 /user/upload
     * @param file 头像文件
     * @return 头像URL
     */
    @PostMapping("/upload")
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {
        log.info("开始上传用户头像 - /user/upload");
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body("用户未登录");
        }
        
        // 获取当前用户名
        String currentUsername = authentication.getName();
        
        // 参数校验
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }
        
        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return ResponseEntity.badRequest().body("文件名不能为空");
        }
        
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!".jpg".equals(suffix) && !".jpeg".equals(suffix) && !".png".equals(suffix) && !".gif".equals(suffix)) {
            return ResponseEntity.badRequest().body("只支持jpg、jpeg、png、gif格式的图片");
        }
        
        try {
            // 上传文件到OSS，指定目录为avatars
            String avatarUrl = fileService.uploadFile(file, "avatars");
            
            // 根据用户名查询用户信息
            User user = userService.lambdaQuery().eq(User::getUsername, currentUsername).one();
            if (user == null) {
                return ResponseEntity.status(404).body("用户不存在");
            }
            
            // 更新用户头像信息
            boolean updated = userService.updateAvatar(user.getId(), avatarUrl);
            if (updated) {
                Map<String, Object> result = new HashMap<>();
                result.put("avatarUrl", avatarUrl);
                result.put("message", "头像上传成功");
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body("更新用户头像失败");
            }
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return ResponseEntity.status(500).body("头像上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 上传用户头像
     * @param file 头像文件
     * @return 头像URL
     */
    @PostMapping("/upload/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        log.info("开始上传用户头像");
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body("用户未登录");
        }
        
        // 获取当前用户名
        String currentUsername = authentication.getName();
        
        // 参数校验
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }
        
        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return ResponseEntity.badRequest().body("文件名不能为空");
        }
        
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!".jpg".equals(suffix) && !".jpeg".equals(suffix) && !".png".equals(suffix) && !".gif".equals(suffix)) {
            return ResponseEntity.badRequest().body("只支持jpg、jpeg、png、gif格式的图片");
        }
        
        try {
            // 上传文件到OSS，指定目录为avatars
            String avatarUrl = fileService.uploadFile(file, "avatars");
            
            // 根据用户名查询用户信息
            User user = userService.lambdaQuery().eq(User::getUsername, currentUsername).one();
            if (user == null) {
                return ResponseEntity.status(404).body("用户不存在");
            }
            
            // 更新用户头像信息
            boolean updated = userService.updateAvatar(user.getId(), avatarUrl);
            if (updated) {
                Map<String, Object> result = new HashMap<>();
                result.put("avatarUrl", avatarUrl);
                result.put("message", "头像上传成功");
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body("更新用户头像失败");
            }
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return ResponseEntity.status(500).body("头像上传失败: " + e.getMessage());
        }
    }
}
